#!/usr/bin/env python

from optparse import OptionParser
from os import chdir, getcwd, listdir, makedirs, pardir, sep
from os.path import abspath, isdir, join
from shutil import copyfile, rmtree
from subprocess import call
from time import altzone, daylight, strftime, timezone

from util import (
    VERSION,
    createSourcePackage,
    getRootDirectory,
    getTemplatesDirectory,
    writeTemplate
)

def main():
    rootDirectory = getRootDirectory()
    distDirectory = abspath(join(rootDirectory, pardir))

    parser = OptionParser("usage: %prog [options]")
    parser.add_option("-d", "--destination-dir", action="store",
                      default=distDirectory, dest="destinationDir",
                      help="Directory to store package in")
    options, args = parser.parse_args()
    if len(args):
        parser.error("incorrect number of required arguments")

    destinationDir = options.destinationDir

    # Add Debian package data to source folder.
    debianTemplateDir = join(getTemplatesDirectory(), "debian")
    debianDir = join(rootDirectory, "debian")
    if isdir(debianDir):
        rmtree(debianDir)
    if daylight:
        zone = altzone
    else:
        zone = timezone
    negativeZone = zone < 0
    if negativeZone:
        sign = '+'
        zone = -zone
    else:
        sign = '-'
    zone /= 60
    offset = "%s%02d%02d" % (sign, zone / 60, zone % 60)
    sepLength = len(sep)
    data = {
        "timestamp": strftime("%a, %d %b %Y %H:%M:%S ") + offset,
        "version": VERSION
    }
    for f in listdir(debianTemplateDir):
        writeTemplate(join(debianDir, f), join(debianTemplateDir, f), data)

    # Build the Debian package.
    oldDirectory = getcwd()
    chdir(rootDirectory)
    try:
        if call(["dpkg-buildpackage", "-us", "-uc"]):
            parser.error("error while building Debian package")

        # Copy .deb files to destination directory.
        if not isdir(destinationDir):
            makedirs(destinationDir)
        fp = open(join(debianDir, "files"))
        try:
            while True:
                line = fp.readline()
                if not line:
                    break
                line = line.strip()
                if not line:
                    continue
                packageName = line[:line.index(".deb ") + 4]
                source = abspath(join(distDirectory, packageName))
                destination = abspath(join(destinationDir, packageName))
                if source != destination:
                    copyfile(source, destination)
        finally:
            fp.close()

    finally:
        chdir(oldDirectory)

if __name__ == "__main__":
   main()
